<template>
 <view class="flex-1 mx-3 mt-3">
	 <view class=" px-3 bg-white" style="border-radius: 20rpx;border-top-width: 4px;" :style="{'border-top-color':$em.$getThemeStyle(['br-color-mian'])['border-top-color']}" > 
		 <view class=" flex flex-row justify-center flex-1" style="z-index: 11; ">
		 	<view style="border-bottom-left-radius: 30rpx;border-bottom-right-radius: 30rpx;" class="px-4 py-1" :style="[$em.$getThemeStyle(['bg-color-mian'])]">
		 		<text style="font-size: 28rpx;color: #fff;font-weight: bold;">评论({{total}})</text>
		 	</view>
		 </view>
		<view v-if="!comment_list.length" style="flex-direction: column;justify-content: center;align-items: center;flex: 1;">
			<text style="font-size: 30rpx;color: #999999;margin: 20rpx;">暂无评论</text>
		</view>
		<view class="flex-1"  v-for="(item,index) in comment_list"  :key="index" :data-index="index" v-if="!item.deleted">
			<view class=" py-1 flex flex-row align-start  border-light-secondary flex-1" >
				<!--  -->
				<view style="width: 70rpx;height: 70rpx;border-radius: 70rpx;">
					<image style="width: 70rpx;height: 70rpx;border-radius: 70rpx;" @click="usershop(item.User)" :src="config.imgUrl+item.User.avatar" ></image>
				</view>
				<view  class="ml-2 flex-1 flex flex-column border-bottom pb-2 flex-1" @longtap="long" >
					<text class="text-hover-primary mb-1" style="color: #A0A0A0;font-weight: 500;font-size: 32rpx;color: #88888B;">{{item.User.nickname}}</text>
					<text v-if="item.content" selectable="true" user-select="true" class="" style="font-size: 34rpx;">{{item.content}}</text>
					<view v-if="item.images" class="mb-1" style="flex-direction: row;justify-content: flex-start;flex-wrap: wrap;">
						<block v-for="(val,index) in item.images" :key="val"  @click="showImage(item.images,index)">
							<image v-if="val" :src="config.imgUrl+val" style="margin: 10rpx 0rpx;margin:2rpx;width: 142rpx;height: 142rpx;border-radius: 8rpx;" mode="aspectFill"/>
						</block>
					</view>
					<view class="flex flex-1 flex-row justify-between mt-1" >
						<view style="flex-direction: row;justify-content: flex-end;"> 
							<text style="font-size: 28rpx;color: #88888B;">{{item.createtime | timestampFormat}}</text>
							<text class="ml-1" @click.stop="doReply(item)"  style="font-size: 28rpx;color: #6F6F6F;">回复</text>
						</view> 
						<view style="flex-direction: row;">
							<view v-if="userInfo.id == item.uid" class="flex flex-row align-center justify-center pr-2" @click="delcomment(item)">
								<em-icon style="font-size: 32rpx;color: #E86262;line-height: 32rpx;" :unicode="'\uec2a'"></em-icon> 
								<text style="color: #E86262;font-size: 26rpx;margin-left: 5rpx;line-height: 26rpx;">删除</text>
							</view>
							<view class="flex flex-row align-center justify-center pr-2" @click="feedback(item)">
								<em-icon style="font-size: 32rpx;color: #AEACB9;line-height: 32rpx;" :unicode="'\ueca1'"></em-icon> 
								<text style="color: #AEACB9;font-size: 26rpx;margin-left: 5rpx;line-height: 26rpx;">举报</text>
							</view>
						</view>
					</view>
					<!-- 回复 -->
					<view style="background-color: #F4F4F4;" class="px-1 rounded mt-1">
						<block  v-for="(reply,index2) in item.reply_list"  :key="index2" :data-index="index2"  v-if="!item.deleted">
							<view class="flex align-start" style="margin-top: 20rpx;">
								<image   @click="usershop(reply.User)" class="reply-user-avatar" :src="config.imgUrl+reply.User.avatar" size="35"></image>
								<view class="pl-2 flex-1 flex flex-column" >
									<!-- <text class="font text-hover-primary mb-1" style="font-weight: 500;color: #848484;">{{reply.User.nickname}}</text> -->
									<text v-if="reply.content" selectable="true" user-select="true" style="font-size: 34rpx;" class="mb-1">{{reply.content}}</text>
									<view style="flex-direction: row;justify-content: flex-start;flex-wrap: wrap;" class="mb-1">
										<block v-for="(val,index) in item.images" :key="val"  @click="showImage(item.images,index)">
											<image v-if="val" :src="config.imgUrl+val" style="margin: 10rpx;width: 142rpx;height: 142rpx;border-radius: 20rpx;" mode="aspectFill"/>
										</block>
									</view> 
									<view class="flex align-center justify-between mb-1" >
										<view style="flex-direction: row;">
											<text style="font-size: 28rpx;color: #88888B;">{{item.createtime | timestampFormat}}</text>
											<text class="ml-1" @click.stop="feedback(reply)" style="font-size: 28rpx;color: #6F6F6F;">举报</text>
											<text class="ml-1" @click.stop="delcomment(reply)" v-if="userInfo.id == reply.uid" style="font-size: 28rpx;color: #6F6F6F;">删除</text>
										</view>
										<view style="flex-direction: row;justify-content: flex-end;" v-if="0"> 
											<view  :hover-stop-propagation="true" @click.stop="doLike(reply)" class="rounded p-1 bg-light cdone"  style="margin-right: 20rpx;flex-direction: row;justify-between;" >
												<n-icon style="margin: 0rpx 5rpx;font-size: 30rpx;line-height: 30rpx;"  class="user-id text-color text-light-muted" name="appreciate_fill_light" size="30" :style="{'color':reply.islike?'#FE6B6C':'#A9A5A0'}"></n-icon>
												<text style="margin: 0rpx 5rpx;font-size: 30rpx;line-height: 30rpx;" class="text-light-muted" :style="{'color':reply.islike?'#FE6B6C':'#A9A5A0'}">{{reply.like_count}}</text>
											</view> 
										</view> 
									</view>
								</view>
							</view>	
						</block>
					</view>
					<view v-if="item.left_comments_count>0" style="flex-direction: row;justify-content: flex-start;">
						<view  :hover-stop-propagation="true" @click.stop="doShowReply(item,item.reply_list)" 
						style="margin-top: 10rpx; margin-right: 20rpx;flex-direction: row;;" >
							<text style="margin: 0rpx 0rpx;font-size: 25rpx;line-height: 30rpx;color:#A9A5A0" >展开{{item.left_comments_count}}条回复</text>
							<em-icon style="margin: 0rpx 2rpx;font-size: 28rpx;line-height: 30rpx;color:#A9A5A0" :unicode="'\uea4e'"></em-icon>
						</view> 
					</view> 
				</view>	
			</view>	
		</view>			
	 </view>
	 <view :style="inputStyles">
		  <comment-box :pid="parent_id"  @published="onpPublished"></comment-box>
	 </view>
	
 </view>
</template>

<script>
	import CommentBox from './comment-box.vue';
  import {
    mapState
  } from 'vuex'
  let app = {}
  // #ifdef MP-WEIXIN
  app = getApp({
    allowDefault: true
  }).$vm
  // #endif
  // #ifndef MP-WEIXIN
  app = getApp({
    allowDefault: true
  })
  // #endif

// #ifdef APP-PLUS
	const animation = weex.requireModule('animation');
	const videframe = uni.requireNativePlugin("sn-videoframe");
	const dom = uni.requireNativePlugin('dom')
// #endif
  export default {
	components: {
		CommentBox
		//pushBtns,mpHtml,specPopup
	},
	props: {
		list: {
			type: Array,
			default: ()=>{
				return []
			}
		},
		total: {
			type: [Number,String],
			default: 0,
		},
	},
    data() {
      return {
		scrollTop:0,
		pushStatus:null,//idle pushing done
		itemList:[],
		pushImagesList:[],
		pushVideoList:[],
		pushPosterList:[],
		content:"",
		subGoods:[],
		goodsList:[],
		id:0,
		form:{
			name:""
		},
		details:{},
		comment_list:this.list,
		parent_id:0,
		chat_bottom:500,
		show_input:true,
      }
    },
	watch:{
		list(nVal,oVal){
			this.comment_list = nVal
		}
	},
    computed: {
      ...mapState([
        'systemInfo',
		'config',
		'userInfo'
      ]),
	  canSend(){
		return true  
	  },
	  inputStyles(){
	  	return `${this.chat_bottom>0?'':''}bottom:${this.chat_bottom}px;position: fixed;`  
	  },
      pageStyles() {
        return {
          wrap: app.$getThemeStyle(['bg-color--1'])
        }
      },
      headerStyles() {
        return {
          wrap: {
            ...app.$getThemeStyle(['bg-color-1', 'shadow-0']),
            'opacity': this.headerOpacity
          },
          title: {
            ...app.$getThemeStyle(['color-1']),
            'opacity': this.headerOpacity
          }
        }
      },
	  addBtns() {
	   return {
	     iconUnicode: '\uea12',
	     styles: {
	       btn: app.$getThemeStyle(['bg-color-103']),
	       icon: app.$getThemeStyle(['color-9'])
	     }
	   }
	  },
	  pushingBtns() {
	   return {
	     iconUnicode: '\ueec3',
	     styles: {
	       btn: app.$getThemeStyle(['bg-color-103']),
	       icon: app.$getThemeStyle(['color-103'])
	     }
	   }
	  },
	  headerLeftBtns() {
	    return [{
	      iconUnicode: '\uea64',
	      styles: {
	        btn: app.$getThemeStyle(['bg-color-102']),
	        icon: app.$getThemeStyle(['color-102'])
	      }
	    }]
	  },
      headerRightBtns() {
        return [{
          name: 'cart',
          iconUnicode: '\uf0b1',
          styles: {
            btn: app.$getThemeStyle(['bg-color-101']),
            icon: app.$getThemeStyle(['color-101'])
          }
        }]
      },
    },
	filters:{
		timestampFormat(timestamp){
			let curTimestamp = parseInt(new Date().getTime() / 1000), //当前时间戳
			timestampDiff = curTimestamp - timestamp, // 参数时间戳与当前时间戳相差秒数
			curDate = new Date( curTimestamp * 1000 ), // 当前时间日期对象
			tmDate = new Date( timestamp * 1000 ),  // 参数时间戳转换成的日期对象
			Y = tmDate.getFullYear(), 
			m = tmDate.getMonth() + 1, d = tmDate.getDate(),
			H = tmDate.getHours(), i = tmDate.getMinutes(), 
			s = tmDate.getSeconds();
			if ( timestampDiff < 60 ) { // 一分钟以内
				return "刚刚";
			} else if( timestampDiff < 3600 ) { // 一小时前之内
				return Math.floor( timestampDiff / 60 ) + "分钟前";
			} else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
				return '今天 ' + ((String(H).length == 1 ? '' : '') + H) + ':' + ((String(i).length == 1 ? '0' : '') + i);
			} else {
				var newDate = new Date( (curTimestamp - 86400) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
				if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
					return '昨天 ' + ((String(H).length == 1 ? '' : '') + H) + ':' + ((String(i).length == 1 ? '0' : '') + i);
				} else if ( curDate.getFullYear() == Y ) {
					return  ((String(m).length == 1 ? '' : '') + m) + '月' + ((String(d).length == 1 ? '0' : '') + d) + '日 '  ;
				} else {
					return  Y + '年' + ((String(m).length == 1 ? '' : '') + m) + '月' + ((String(d).length == 1 ? '0' : '') + d) + '日 ' + ((String(H).length == 1 ? '' : '') + H) + ':' + ((String(i).length == 1 ? '0' : '') + i);
				}
			}
		}
	},
    async created() {
      this.$em = app.$em
	  await this.$nextTick()
	  uni.$on('onKeyboard_height_change',res =>{
		  let _sysInfo = this.systemInfo;
		  let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight;
	  	if (this.show_input) {
	  		if (res.height <= 1) {
	  			this.chat_bottom = 0;
	  			this.show_input = false;
	  			this.parent_id = 0;
	  			this.placeholder = ''; 
	  		} else {
	  			let _diff = res.height - _heightDiff;
	  			this.chat_bottom = _diff > 0 ? _diff : 0;
	  			this.show_input = true;
	  		}
	  	}
	  });
    },
    onLoad(e) {
    },
	onShow() {
		//this.content = uni.getStorageSync("MP-HTML-EDIT") || ""
	},
    methods: {
	  showImages(images,index){
	  	   uni.previewImage({
	  	        urls:  images.map(image => this.config.imgUrl + image), // 图片列表的url数组
	  	        current: index, // 当前图片的索引
	  	        loop: true, // 是否开启循环预览
	  	        longPressActions: { // 可选的长按菜单操作
	  	          itemList: ['发送给朋友', '保存图片'],
	  	          success: res => {
	  	            console.log(res.tapIndex)
	  	          }
	  	        }
	  	      })
	  },
	  addAlbum(){
	  	let _this = this
		uni.hideKeyboard()
	  		let menus = [];
			menus.push({
					name:"添加图片",
					//iconUnicode:'\uea58',
					event:()=>{
						this.$refs.confirm.close();
						uni.chooseImage({
							count: 9,  
							sizeType: ['compressed'], 
							sourceType: ['album'],
							success: function  (res) {
								res.tempFilePaths.map((val)=>{
									_this.upload(val,'images')
								})
							}
						})	
					}			
			})
			this.$refs.confirm.open({
				menus:menus,		  
				duration:3000,
				confirm:()=>{}		  
			})
	  },
	  addAlbum1(type = ""){
	  	let _this = this
		if(type == "poster"){
			uni.chooseImage({
				count: 1,  
				sizeType: ['compressed'], 
				sourceType: ['album'],
				success: function  (res) {
					res.tempFilePaths.map((val)=>{
						_this.upload(val,type)
					})
				}
			})	
			return;
		}
		if(type == "images"){
			uni.chooseImage({
				count: 99,  
				sizeType: ['compressed'], 
				sourceType: ['album'],
				success: async (res)=> {
					let filePaths = res.tempFilePaths
					 for (let i = 0; i < filePaths.length; i++) {
					     this.upload(filePaths[i]);
						 await uni.sleep(500)
					  }
					/* res.tempFilePaths.map((val)=>{
						_this.upload(val,type)
					}) */
				}
			})	
			return;
		}
		
		
		let menus = [];
		if(this.pushVideoList.length == 0){
			menus.push({
				name:"添加视频",
				event:()=>{
					this.$refs.confirm.close();
					uni.chooseVideo({  //打开选择视频 
						compressed:false,
						sourceType: ['album'],  //直接打开选择视频 ['album','camera'] 就会弹出选框
						success: function (res) {
							//_this.upload(res.tempFilePath,'videos')
							videframe.getFrame({
							    url: res.tempFilePath,
								time:2,
							 },(e) => {
							    if (e.code == 0) {
								  _this.upload(e.imagePath,'videoAndThumb',{
								  	size:res.size,
								  	duration:res.duration,
								  	width:res.width,
								  	height:res.height,
									outPath:res.tempFilePath
								  })  
							    }else{
							      uni.showToast({title: e.msg, icon: "none"});
							    }            
							 })
							
						}
					})
					
				}					
			})
		}
		
		menus.push({
				name:"添加图片",
				//iconUnicode:'\uea58',
				event:()=>{
					this.$refs.confirm.close();
					uni.chooseImage({
						count: 9,  
						sizeType: ['compressed'], 
						sourceType: ['album'],
						success: function  (res) {
							res.tempFilePaths.map((val)=>{
								_this.upload(val)
							})
						}
					})	
				}			
		})
		this.$refs.confirm.open({
			menus:menus,		  
			duration:3000,
			confirm:()=>{}		  
		})
		
	  	 
	  },
	  async upload(path,type="images",info = {}){
	  	const res = await uni.$http.upload("/api/user/upload",{},path)
	  	if(!res.data)return;
		if(type == 'images'){
			this.pushImagesList.push(res.data.url)
			
		}
		if(type == 'videoAndThumb'){
			info.thumb = res.data.url;
			this.upload(info.outPath,'videos',info)
			delete info.outPath
		}
	  	if(type == 'videos'){
	  		this.pushVideoList.push({
				url:res.data.url,
				...info
			})
	  	}
	  	if(this.pushVideoList.length || this.pushImagesList.length){
	  		this.pushStatus = 'idle'
	  	}
	  	console.log("res",this.pushImagesList)
		this.$forceUpdate()
	  },
	  deleteItem(list,index){
		list.splice(index,1);
	  	if(!this.pushVideoList.length && !this.pushImagesList.length){
	  		this.pushStatus = null
	  	}
	  },
      scroll(e) {
        let scrollTop = e.scrollTop <= 0 ? 0 : e.scrollTop
        let transparentHeight = (this.systemInfo.windowWidth * 0.68 + this.systemInfo.statusBarHeight) / 2
        let opacityCoefficient = scrollTop / transparentHeight
        let opacity = opacityCoefficient > 1 ? 1 : opacityCoefficient
        //this.headerOpacity = opacity
        if (e.scrollBottom <= 250) {
         // this.loadmore()
        }
      },
	  getComponentRect(refs){  	 
		return  new Promise((resolve, reject) => {
			dom.getComponentRect(refs, rect => {
			     resolve(rect.size.height)
			   })
			})	  
	  },
	 async create(){
			if(this.pushImagesList.length == 0 && this.pushVideoList.length == 0 && !this.content){
				uni.showToast({
				  icon: 'none',
				  title: '您未上传任何图片或视频哦'
				})
				return
			}
			let params = {
				images:this.pushImagesList.join(","),
				videos:JSON.stringify(this.pushVideoList),
				content:this.content
			}
			console.log("this.goodsList",this.goodsList)
			if(this.goodsList.length>0){
				params.gid = this.goodsList[0].id
			}
			
			 uni.$http.post("/api/circle/push",params)
			 .then(()=>{
				this.pushImagesList = []
				this.content = ""
				this.$emit("published",{})
				setTimeout(()=>{
					uni.showToast({
					  icon: 'none',
					  title: '添加成功'
					})
				},0) 
			 })
			 .catch(err=>{
			 })
	 },
     async clickHeaderBtn(e) {
		  console.log("e",e)
		  console.log("scrollTop",this.scrollTop)
		if (e.position === 'left' && e.index === 0) {
		    app.$navigateBack()
		}
        if (e.position === 'right' && e.index === 0) {
			this.create()
		}
      }
    }
  }
</script>

<style>
  .btn-send {
  	border-radius: 15rpx;font-size: 22rpx;color: #FFFFFF;height: 64rpx;line-height: 64rpx;width: 100rpx;text-align: center;
  }
  
  .chat-body {
  	position: fixed;width: 750rpx;padding: 10rpx; background-color: #FFFFFF;
  }
  
  .chat-input {
  	background-color: #F2EEEE;
  	border-radius: 15rpx; 
  	font-size: 26rpx;
  	height: 66rpx;
  	line-height: 66rpx;
  }

  
  .reply-user-avatar{
  	width: 40rpx;
  	height: 40rpx;
  	border-radius: 8rpx;
  }
  .border-bottom{
  	border-bottom-width: 0px;
  	border-style: solid;
  }
</style>
